package com.house.framework.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.house.exception.MyException;
import com.house.framework.dto.UserDto;
import com.house.framework.entity.Logininfo;
import com.house.framework.entity.User;
import com.house.framework.mapper.LogininfoMapper;
import com.house.framework.mapper.UserMapper;
import com.house.framework.service.IUserService;
import com.house.framework.utils.AjaxResult;
import com.house.framework.vo.UserVo;
import com.house.utils.MD5Utils;
import com.house.utils.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @ClassName UserServiceImpl
 * @Date 2021/10/17 15:23
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     *@Description 手机注册
     *@Param
     *@Return 
     */
    @Transactional
    @Override
    public void phoneRegister(UserDto userDto) {
        // 校验
        // 1.非空校验 4个
        if (StringUtils.isEmpty(userDto.getUserName()) || StringUtils.isEmpty(userDto.getPassword()) || StringUtils.isEmpty(userDto.getComfirmPwd())) {
            throw new MyException("参数不能为空");
        }
        // 2.手机号是否被注册
        User tmpUser = userMapper.findByPhone(userDto.getUserName());
        if (tmpUser != null) {
            throw new MyException("账号已经注册，请直接登录");
        }
        // 3.两次密码是否正确
        if (!userDto.getPassword().equals(userDto.getComfirmPwd())) {
            throw new MyException("两次密码不一致...");
        }
        // 4.验证码校验
//        Object obj = redisTemplate.opsForValue().get(UserConstant.REGISTER_PREFIX + userDto.getPhone());
//        if (obj == null) {
//            throw new MyException("验证码过期，请重新获取");
//        } else {
//            // 取出验证码，不区分大小写验证
//            String redisCode = obj.toString().split(":")[1];
//            if (!redisCode.equalsIgnoreCase(userDto.getCode())) {
//                throw new MyException("验证码错误，请重新输入");
//            }
//        }

        // 5.把数据保存到t_user,t_logininfo 表
        // 准备user数据和logininfo数据
        User user = userDto2User(userDto); //
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.add(logininfo); // 返回主键自增
        user.setLogininfo_id(logininfo.getId());
        userMapper.add(user);
    }

    @Transactional
    @Override
    public void dataModification(User user) {
        User byId = userMapper.selectById(user.getId());
        Long logininfoId = byId.getLogininfo_id();
        // 盐值随机生成
        String salt = StrUtils.getComplexRandomString(32);
        // 密码：加密加盐
        String password = MD5Utils.encrypByMd5(user.getPassword() + salt);
        Logininfo logininfo = new Logininfo();
        logininfo.setId(byId.getLogininfo_id());
        if (StringUtils.isNotEmpty(user.getPassword())) {
            user.setPassword(password);
            user.setSalt(salt);
            logininfo.setPassword(user.getPassword());
            logininfo.setSalt(user.getSalt());
        } else {
            logininfo.setPhone(user.getPhone());
        }
        logininfoMapper.updateById(logininfo);
        userMapper.updateById(user);
    }

    @Transactional
    @Override
    public void deleteUserById(Long id) {
        User user = userMapper.selectById(id);
        Long logininfoId = user.getLogininfo_id();
        logininfoMapper.deleteById(logininfoId);
        userMapper.deleteById(id);
    }

    @Override
    public IPage<UserVo> userListPaging(UserVo user) {
        int pageIndex = user.getPageIndex();
        int pageSize = user.getPageSize();
        IPage page = new Page<UserVo>(pageIndex, pageSize);
        QueryWrapper<UserVo> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(Objects.nonNull(user.getDisable()), "a.disable", user.getDisable())
                .eq(Objects.nonNull(user.getType()), "a.type", user.getType())
                .eq(StringUtils.isNotEmpty(user.getUsername()), "t.username", user.getUsername())
                .orderByAsc("t.id");
        return userMapper.page(page, queryWrapper);
    }

    @Override
    @Transactional
    public Object userUpdate(UserVo user) {
        Logininfo logininfo = new Logininfo();
        User byId = userMapper.selectById(user.getId());
        logininfo.setId(byId.getLogininfo_id());
        int i = 0;
        if (StringUtils.isNotEmpty(user.getPassword())) {
            // 盐值随机生成
            String salt = StrUtils.getComplexRandomString(32);
            // 密码：加密加盐
            String password = MD5Utils.encrypByMd5(user.getPassword() + salt);
            user.setSalt(salt);
            user.setPassword(password);
            logininfo.setSalt(salt);
            logininfo.setPassword(password);
            i = 1;
        }
        if (Objects.nonNull(user.getType())) {
            logininfo.setType(user.getType());
            i = 1;
        }
        if (Objects.nonNull(user.getDisable())) {
            logininfo.setDisable(user.getDisable());
            i = 1;
        }
        User user1 = new User();
        BeanUtils.copyProperties(user, user1);
        userMapper.updateById(user1);
        if (i == 1) {
            logininfoMapper.updateById(logininfo);
        }
        return AjaxResult.me().setMsg("修改成功！");
    }

    @Transactional
    @Override
    public Object userAdd(UserVo user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUsername, user.getUsername());
        Long aLong = userMapper.selectCount(wrapper);
        if (aLong > 0) {
            return AjaxResult.me().setSuccess(false).setMsg("账号已存在，请勿重复添加！");
        }
        // 盐值随机生成
        String salt = StrUtils.getComplexRandomString(32);
        // 密码：加密加盐
        String password = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(password);
        User user1 = new User();
        BeanUtils.copyProperties(user, user1);
        Logininfo logininfo = user2Logininfo(user1);
        logininfo.setDisable(user.getDisable());
        logininfo.setType(user.getType());
        logininfoMapper.add(logininfo);
        user1.setLogininfo_id(logininfo.getId());
        userMapper.insert(user1);
        return AjaxResult.me().setMsg("新增成功！");

    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        // copy user中的数据到logininfo中
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(0);
        logininfo.setDisable(1);
        return logininfo;
    }

    public User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getUserName());
        user.setName(userDto.getName());
        user.setState(1);
        user.setPhone(userDto.getPhone());
        user.setUserType(0);
        // 盐值随机生成
        String salt = StrUtils.getComplexRandomString(32);
        // 密码：加密加盐
        String password = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(password);
        return user;
    }
}